<template>
	<div class="table-box">
		<proTable
			ref="proTableRef"
			:columns="columns"
			:toolButton="false"
			:requestApi="roleInfoApi.GetRoleInfoPage"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<template #tableHeader>
				<el-button type="primary" @click="addroleclick" :icon="CirclePlus">新增角色</el-button>
			</template>
			<template #operation="scope">
				<el-space>
					<el-tag style="cursor: pointer" @click="editTable(scope.row)">编辑</el-tag>
					<el-tag style="cursor: pointer" @click="permissionSettings(scope.row)">权限设置</el-tag>
					<el-tag style="cursor: pointer" @click="handlestates(scope.row)" :type="scope.row.states ? 'danger' : ''"
						>{{ scope.row.states ? "禁用" : "启用" }}
					</el-tag>
				</el-space>
			</template>
			<template #competitionName="scope">
				{{ scope.row.competitionName }}
			</template>
			<template v-if="!isPlatform" #companyName="scope">
				{{ scope.row.companyName }}
			</template>
		</proTable>
		<el-dialog @closed="handleCancelClick(ruleFormRef)" v-model="addUserModel" width="40%" :title="edittitle">
			<el-form ref="ruleFormRef" :model="addUserForm" :rules="rules" label-width="150" label-position="right">
				<el-form-item label="角色名称：" prop="RoleName">
					<el-input style="width: 50%" v-model="addUserForm.RoleName" placeholder="请输入" />
				</el-form-item>
				<el-form-item required label="所属商户：" v-if="!isPlatform">
					<el-select v-model="addUserForm.CompanyId">
						<el-option label="平台端" value="" />
						<el-option v-for="item in CompanyInfo" :key="item.CompanyId" :label="item.CompanyName" :value="item.CompanyId" />
					</el-select>
				</el-form-item>
				<el-form-item label="状态：">
					<el-radio-group v-model="addUserForm.States">
						<el-radio :label="1">启用</el-radio>
						<el-radio :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleCancelClick(ruleFormRef)">取消</el-button>
					<el-button type="primary" @click="addRoleInfo(ruleFormRef)"> 保存角色 </el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 权限设置 -->
		<el-dialog @closed="handlePermissiClose" v-model="Permissi.isShow" width="80%" title="权限设置">
			<el-card>
				<template #header>
					<el-form :inline="true" :model="functionquerySearch" class="demo-form-inline">
						<el-form-item label="菜单编号：">
							<el-select
								style="width: 170px; margin-right: 15px"
								v-model="functionquerySearch.FunctionNumber"
								placeholder="菜单编号"
								filterable
							>
								<el-option label="全部" value="" />
								<el-option
									v-for="item in functionNumberList"
									:key="item.functionNumber"
									:label="item.functionNumber"
									:value="item.functionNumber"
								/>
							</el-select>
						</el-form-item>
						<el-form-item label="菜单名称：">
							<el-input v-model="functionquerySearch.FunctionName" placeholder="菜单名称" />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="searchOperationRoleFunction">查询</el-button>
							<el-button type="info" @click="resetOperationRoleFunction">重置</el-button>
						</el-form-item>
					</el-form>
				</template>
				<el-table :data="functiontableData" border max-height="600">
					<el-table-column property="id" label="序号" width="200px" v-if="false" align="center" />
					<el-table-column label="选择" align="center" width="85">
						<template #default="scope">
							<el-checkbox v-model="scope.row.isPermission" @change="checkboxchange(scope.row)" />
						</template>
					</el-table-column>
					<el-table-column property="functionNumber" label="菜单编号" width="200" align="center" />
					<el-table-column property="functionName" label="菜单名称" width="200" align="center" />
					<el-table-column property="parentNumber" label="上级编号" align="center" />
					<el-table-column property="parentName" label="上级名称" align="center" />
					<el-table-column property="functionTypeName" label="类型" align="center" />
				</el-table>
				<el-pagination
					v-model:currentPage="functionquerySearch.PageIndex"
					v-model:page-size="functionquerySearch.PageSize"
					:page-sizes="[10, 20, 50, 100]"
					layout="total, sizes, prev, pager, next, jumper"
					:total="Permissi.total"
					@size-change="Permissi.handleSizeChange"
					@current-change="Permissi.handleCurrentChange"
				/>
			</el-card>
		</el-dialog>
	</div>
</template>

<script lang="tsx" setup>
import type { FormInstance, FormRules } from "element-plus";
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, ref, computed } from "vue";
import { CirclePlus } from "@element-plus/icons-vue";
import roleInfoApi from "@/api/modules/roleInfo";
import companyInfoApi from "@/api/modules/companyInfo";
import { ColumnProps } from "@/components/ProTable/interface";
import proTable from "@/components/ProTable/index.vue";
import { GlobalStore } from "@/stores";
const globalStore = GlobalStore();
let isPlatform = globalStore.isPlatform;
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref();
// const router = useRouter();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	Order: "",
	Sort: ""
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	return {
		list: data.data,
		total: data.totalCount
	};
};
// 商户选项
const getCompanysList = async () => {
	let { result } = await companyInfoApi.GetCompanyNameList();
	let { data } = result as any;
	data.unshift({ companyName: "全部", id: "" });
	return result;
};
// 表格配置项
const columns = computed((): Partial<ColumnProps>[] => {
	let data: Partial<ColumnProps>[] = [
		{
			prop: "companyName",
			label: "赛事创建商户",
			render: (scope: { row: any }) => {
				return <> {scope.row.companyName || "平台端"} </>;
			}
		},
		{
			prop: "companyId",
			label: "赛事创建商户",
			isShow: false,
			enum: getCompanysList,
			search: { el: "select", props: { filterable: true }, defaultValue: "" },
			fieldNames: { label: "companyName", value: "id" }
		},
		{ prop: "roleName", label: "角色名称", search: { el: "input" } },
		{
			prop: "states",
			label: "状态",
			render: (scope: { row: any }) => {
				return <> {<el-tag type={scope.row.states ? "" : "danger"}>{scope.row.states ? "启用" : "禁用"}</el-tag>} </>;
			}
		},
		{ prop: "createUserName", label: "创建人" },
		{ prop: "createTime", label: "创建时间" },
		{ prop: "operation", label: "操作", width: 220, fixed: "right" }
	];
	if (isPlatform) {
		data = data.filter(i => {
			return i.prop != "companyName" && i.prop != "companyId";
		});
		return data;
	}
	return data;
});
//所有角色表格数据
const tableData = ref<Array<any>>([]);
//所有操作员拥有的功能
const functiontableData = ref<Array<any>>([]);
//菜单编号集合
const functionNumberlist = ref<Array<any>>([]);
//功能菜单编号集合
const functionNumberList = ref<Array<any>>([]);
//权限设置弹窗
const Permissi = reactive({
	isShow: false,
	total: 100,
	handleSizeChange: () => {
		searchOperationRoleFunction();
	},
	handleCurrentChange: () => {
		getOperationRoleFunction();
	}
});

//获取角色请求
const querySearch = reactive({
	PageIndex: 1,
	PageSize: 10,
	Order: "",
	Sort: "",
	RoleName: "", //角色名称
	CompanyId: ""
});

interface CompanyItem {
	CompanyId: string;
	CompanyName: string;
}
const CompanyInfo = ref<CompanyItem[]>([]);

//获取客户名称集合
const getCompanyNameList = () => {
	companyInfoApi.GetCompanyNameList().then(ret => {
		let resposen = JSON.parse(JSON.stringify(ret));
		if (resposen.result && resposen.result.isSuccess && resposen.result.code == 200) {
			let data = JSON.parse(JSON.stringify(resposen.result.data));
			data.forEach((element: any) => {
				CompanyInfo.value.push({
					CompanyId: element.id,
					CompanyName: element.companyName
				});
			});
		}
	});
};

getCompanyNameList();
//获取功能请求
const functionquerySearch = reactive({
	PageIndex: 1,
	PageSize: 10,
	Order: "",
	Sort: "",
	FunctionName: "", //功能菜单名称
	FunctionNumber: "", //功能菜单编号
	PermissionSettingsRoleId: ""
});
//获取表格列表信息
const getroleTableData = async () => {
	tableData.value = [];
	let res = await roleInfoApi.GetRoleInfoPage(querySearch);
	let { data } = res.result;
	tableData.value = data;
	pagination.total = res.result.totalCount;
};
getroleTableData();
//查询操作
const searchroleinfo = () => {
	querySearch.PageIndex = 1;
	//querySearch.PageSize = 10;
	pagination.total = 0;
	getroleTableData();
};
//分页
const pagination = reactive({
	total: 0,
	handleSizeChange: () => {
		searchroleinfo();
	},
	handleCurrentChange: () => {
		getroleTableData();
	}
});

const addUserModel = ref<boolean>(false);
const addUserForm = reactive({
	RoleName: "",
	CompanyId: "",
	States: 1
});

//保存角色按钮操作，1新增，2编辑
const addOrUpdate = ref("");
//更新的角色id
const roleupdateid = ref("");
//新增还是编辑弹出框标题
const edittitle = ref("");

//新增角色
const addroleclick = () => {
	addOrUpdate.value = "1";
	edittitle.value = "添加角色";
	addUserForm.RoleName = "";
	if (isPlatform == true) {
		addUserForm.CompanyId = "";
	} else {
		addUserForm.CompanyId = querySearch.CompanyId;
	}
	addUserForm.States = 1;
	addUserModel.value = true;
};

const ruleFormRef = ref();
//保存角色
const addRoleInfo = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (valid) {
			if (addOrUpdate.value == "1") {
				roleInfoApi.AddRoleInfo(addUserForm).then(ret => {
					let resposen = JSON.parse(JSON.stringify(ret));
					if (resposen.result && resposen.result.isSuccess && resposen.result.code == 200) {
						ElMessage.success("添加成功！");
						addUserForm.RoleName = "";
						addUserForm.States = 1;
						addUserForm.CompanyId = "";
						addUserModel.value = false;
						proTableRef.value.getTableList();
					} else {
						ElMessageBox.alert("添加失败：" + resposen.result.message);
					}
				});
			} else {
				roleInfoApi
					.UpdateRoleInfo({
						Id: roleupdateid.value,
						RoleName: addUserForm.RoleName,
						CompanyId: addUserForm.CompanyId,
						States: addUserForm.States
					})
					.then(ret => {
						let resposen = JSON.parse(JSON.stringify(ret));
						if (resposen.result && resposen.result.isSuccess && resposen.result.code == 200) {
							ElMessage.success("修改成功！");
							addUserForm.RoleName = "";
							addUserForm.States = 1;
							addUserForm.CompanyId = "";
							addUserModel.value = false;
							proTableRef.value.getTableList();
						} else {
							ElMessageBox.alert("修改成功：" + resposen.result.message);
						}
					});
			}
		} else {
			return false;
		}
	});
};
//禁用/启用用户状态
const handlestates = (val: any) => {
	ElMessageBox.confirm("确定将“" + val.roleName + "”" + (val.states ? "禁用" : "启用") + "?", "状态更改", {
		confirmButtonText: "确认",
		cancelButtonText: "取消"
	}).then(() => {
		roleInfoApi
			.RoleInfoBatchChangeOfStatus({
				States: val.states ? false : true,
				List: [{ Id: val.id }]
			})
			.then(ret => {
				let resposen = JSON.parse(JSON.stringify(ret));
				if (resposen.result && resposen.result.isSuccess && resposen.result.code == 200) {
					ElMessage.success((val.states ? "禁用" : "启用") + "成功");
					getroleTableData();
					proTableRef.value.getTableList();
				} else {
					ElMessageBox.alert((val.states ? "禁用" : "启用") + "失败" + resposen.result.message);
					getroleTableData();
					proTableRef.value.getTableList();
				}
			});
	});
};

//编辑用户
const editTable = (val: any) => {
	addOrUpdate.value = "2";
	edittitle.value = "编辑角色";
	roleupdateid.value = val.id;
	addUserForm.RoleName = val.roleName;
	addUserForm.States = val.states == true ? 1 : 0;
	addUserForm.CompanyId = val.companyId == null ? "" : val.companyId;
	addUserModel.value = true;
};

//权限设置按钮
const permissionSettings = (val: any) => {
	Permissi.isShow = true;
	functionNumberlist.value = [];
	functionquerySearch.FunctionNumber = "";
	functionquerySearch.FunctionName = "";
	functionquerySearch.PermissionSettingsRoleId = val.id;
	getOperationRoleFunction();
	getfunctionNumberList();
};

//获取操作员拥有的所有权限
const getOperationRoleFunction = async () => {
	//获取表格列表信息
	functiontableData.value = [];
	let res = await roleInfoApi.GetRoleFunctionList(functionquerySearch);
	let { data } = res.result;
	functiontableData.value = data;
	Permissi.total = res.result.totalCount;
	//console.log(JSON.stringify(data));
};
//查询操作
const searchOperationRoleFunction = () => {
	functionquerySearch.PageIndex = 1;
	Permissi.total = 0;
	getOperationRoleFunction();
};

//重置操作
const resetOperationRoleFunction = () => {
	functionquerySearch.FunctionName = ""; //功能菜单名称
	functionquerySearch.FunctionNumber = ""; //功能菜单编号
};

const getfunctionNumberList = async () => {
	//获取表格列表信息
	functionNumberList.value = [];
	let res = await roleInfoApi.GetFunctionNumberList();
	let { data } = res.result;
	functionNumberList.value = data;
};

//复选框选择状态
const checkboxchange = async (val: any) => {
	let res = await roleInfoApi.AddOrUpdateRoleFunction({
		RoleId: functionquerySearch.PermissionSettingsRoleId,
		List: [{ FunctionId: val.id, States: val.isPermission }]
	});
	if (res.result && res.result.isSuccess && res.result.code == 200) {
		let msg = val.isPermission ? "新增成功！" : "取消成功！";
		ElMessage.success(msg);
	} else {
		ElMessage.error("设置失败！");
	}
};

// const handleSelectionChange = () => {
// 	//console.log(val);
// };

const rules = reactive<FormRules>({
	RoleName: [
		{
			required: true,
			message: "请输入角色名称",
			trigger: "blur"
		}
	]
});
//取消保存角色
const handleCancelClick = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	addUserModel.value = false;
};
//关闭权限设置弹框
const handlePermissiClose = () => {
	functionquerySearch.PageIndex = 1;
	functionquerySearch.PageSize = 10;
};
</script>

<style lang="scss" scoped>
::v-deep.box-card {
	.card-header {
		display: flex;
		justify-content: space-between;

		.headerQuery {
			display: flex;
		}
	}
}

.addUser {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}

::v-deep.tableBox {
	display: flex;
	flex-direction: column;
	align-items: flex-end;

	.el-space__item {
		cursor: pointer;
	}
}
</style>
